<?php

namespace Frieza\Modules\Live\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\service\Live\AdmContentCard;
use Encore\Admin\Widgets\Form;
use Doraemon\model\Live\LiveContentCard as mLiveContentCard;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\tools\BlockTypeMapping;
use Illuminate\Support\MessageBag;
use Doraemon\tools\LinkFormat;
use Doraemon\cache\Live\ContentCard as cacheContentCard;




class ContentCardController extends Controller
{
    const PAGE_SIZE = 20;

    const ALLOW_LINK = [
        LinkConf::LINK_PHOTO,
        LinkConf::LINK_ARTICLE,
        LinkConf::LINK_BLANK,
        LinkConf::LINK_GUIDE,
        LinkConf::MALL_WIKI_DETAIL,
        LinkConf::LINK_APP_COURSE_DETAIL,
        LinkConf::LINK_APP_LIVE_DETAIL,
        LinkConf::LINK_H5_HTTPS
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $where= [];
        if($request->input('op_type')){
            $where['op_type'] = $request->input('op_type');
        }
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['ORDER'] = ['sort' => 'DESC'];
        $where['card_status'] = mLiveContentCard::STATUS_NORMAL;
        $list = AdmContentCard::getCardList($where);

        $result['list'] = $list;
        unset($where['LIMIT']);
        $result['total'] = mLiveContentCard::count($where);

        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableFilter();
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->width(40);
                $grid->column('title', '标题')->width(80);
                $grid->column('sort', '权重');
                $grid->column('op_type', '类型')->width(100);
                $grid->column('link', '链接地址')->width(250)->linkSelect(false, null, false);
                $grid->column('cover_img', '封面')->image($this->cover_img, 100, 100);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                  //  $actions->disableDelete();
                });
            }
        );
        $tab = new Tab();
        $tab->add('内容卡片列表', $gridList->render(), true);
        $tab->addLink('内容模块名称', url('/admin/live/contentcard/settitle'), false);
        return $content->header('内容卡片列表')->breadcrumb(
            ['text' => '内容卡片列表'])
            ->row($tab);

    }


    /*创建栏目
     *
     * */
    public function create(Request $request, Content $content, $id = 0)
    {
        $header = '添加内容卡片';
        if ($id) {
            $header = '编辑内容卡片';
        }
        $info  = $id ? mLiveContentCard::getByWhere(['id' => $id] ) :[];
        if($info){
            $bannerLink = LinkFormat::generateLink($info['link_type'], $info['link_params']);
            $link = ($bannerLink && isset($bannerLink['app_template'])) ? $bannerLink['app_template'] : '';
            $info['link'] =[
                'link_type' => $info['link_type'],
                'link_params' => $info['link_params'],
                'link_url' => $link,
            ];
        }

        $form = new Form($info);
        $form->hidden('id');
        $form->text('title', '标题')->required();
        $form->number('sort', '权重')->default(0);
        $form->radio('is_show' , '是否公开') ->options(mLiveContentCard::TYPE_SHOW)->default(1);
        $form->radio('op_type' , '卡片类型') ->options(mLiveContentCard::TYPE_MAP)->required();
        $form->multiLinkSelect('link', '跳转地址', self::ALLOW_LINK);
        $form->imgUpload('cover_img', '封面图')->help('必传');
        $form->action(url('admin/live/contentcard/save'));
        $content->row($form);
        return $content->header($header)->breadcrumb(
            ['text' => '内容卡片列表', 'url' => url('admin/live/contentcard')],
            ['text' => $header]);
    }


    /*添加成功
     *
     * */
    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $id = isset($params['id']) ? $params['id'] : 0;
            $data = [
                'title' => $params['title'],
                'cover_img' => $params['cover_img'] ? $params['cover_img'] : '',
                'card_status' => mLiveContentCard::STATUS_NORMAL,
                'sort' => $params['sort']?: 0,
                'admin_id' => Admin::user()->id,
                'op_type' => $params['op_type'],
                'is_show' => $params['is_show']
            ];
            if (empty($request->input("link", []))) {
                throw new \Exception('输入连接');
            }
            $obj = $request->input("link", []);
            $link_type = $obj['link_type'] ?? '';
            $data['link_type'] = $link_type;
            $link_params = isset($obj['link_params']) ? json_encode($obj['link_params'], JSON_UNESCAPED_UNICODE) : '';
            $data['link_params'] = $link_params;
            $objRs = BlockTypeMapping::getObjFromLinkParams($link_type, $link_params);
            if($objRs['obj_id']){
                $obj_id = $objRs['obj_id'] ?? null;
                $data['obj_id'] = $obj_id;
            }

            if(in_array($link_type , [ LinkConf::MALL_GOODS_DETAIL, LinkConf::LINK_APP_COURSE_DETAIL,LinkConf::LINK_APP_LIVE_DETAIL])){
                $objRs = json_decode($link_params , true);
                if($objRs['room_id']){
                    $obj_id = $objRs['room_id'] ?? null;
                    $data['obj_id'] = $obj_id;
                }
                if($objRs['course_id']){
                    $obj_id = $objRs['course_id'] ?? null;
                    $data['obj_id'] = $obj_id;
                }
                if($objRs['goods_id']){
                    $obj_id = $objRs['goods_id'] ?? null;
                    $data['obj_id'] = $obj_id;
                }
            }

            if($link_type == LinkConf::LINK_H5_HTTPS){
                $data['obj_id'] = '';
            }

            if (empty($data['title'])) {
                throw new \Exception('必须设置栏目名称');
            }

            if (empty($data['cover_img'])) {
                throw new \Exception('必须上传封面');
            }
            if($id){
                $result = mLiveContentCard::updateData($data , ['id' => $id]);
            }else{
                $result =  mLiveContentCard::insertData($data);
            }
            if ($result) {
                $url = url('/admin/live/contentcard');
                return redirect($url)->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage(), $e->getFile(), $e->getLine());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }


    public function deletecard(Request $request, $id = 0)
    {
        try {
            if ($id ) {
                mLiveContentCard::updateData(['card_status' => mLiveContentCard::STATUS_DEL ,'admin_id' => Admin::user()->id], ['id' => $id]);
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                throw new \Exception('不存在的id');
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json($success);
    }


    public function setTitle(Request $request,Content $content)
    {
        $info = [];
        $title = cacheContentCard::getTitle();
        if($title){
            $info['title'] = $title;
        }
        $form = new Form($info);
        $form->text('title', '标题')->required();
        $form->action(url('admin/live/contentcard/savetitle'));
        $content->row($form);
        return $content->header('模块名称')->breadcrumb(
            ['text' => '内容卡片列表', 'url' => url('admin/live/contentcard')],
            ['text' => '模块名称'])
           ;
    }

    /*添加成功
     *
     * */
    public function saveTitle(Request $request)
    {
        try {
            $params = $request->all();
            cacheContentCard::addTitle($params['title']);
            $url = url('/admin/live/contentcard/setTitle');
            return redirect($url)->with(compact('success'));
        } catch (\Exception $e) {
            Log::debug($e->getMessage(), $e->getFile(), $e->getLine());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }











}